<?php
namespace app\exception;

use Throwable;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\Exception\ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * 不需要记录日志的异常
     * @var array
     */
    public $dontReport = [
        BusinessException::class,
    ];

    /**
     * 异常处理
     * @param Throwable $exception
     * @param Request $request
     * @return Response
     */
    public function render(Request $request, Throwable $exception): Response
    {
        // Apidoc异常处理响应
        if ($exception instanceof \hg\apidoc\exception\HttpException) {
            return response(json_encode([
                "code" => $exception->getCode(),
                "message" => $exception->getMessage(),
            ],JSON_UNESCAPED_UNICODE), $exception->getStatusCode());
        }

        return parent::render($request, $exception);
    }

    /**
     * 记录日志
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception)
    {
        if ($this->shouldntReport($exception)) {
            return;
        }

        $logs = [
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => $exception->getTraceAsString(),
            'previous' => $exception->getPrevious(),
        ];

        if (method_exists($exception, 'getData')) {
            $logs['data'] = $exception->getData();
        }

        error_log(json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }

    /**
     * 判断是否不需要记录日志
     * @param Throwable $e
     * @return bool
     */
    protected function shouldntReport(Throwable $e): bool
    {
        foreach ($this->dontReport as $type) {
            if ($e instanceof $type) {
                return true;
            }
        }
        return false;
    }
} 